package day05;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * 生产者&消费者
 */
public class ArrayBlockingQueueExample02 {

    public static void main(String[] args) {
        ArrayBlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(10);

        IntStream.rangeClosed(0, 10)
                .boxed()
                .map(integer -> new Thread("Thread-" + integer) {
                    @Override
                    public void run() {
                        while (true) {
                            try {
                                String put = "a-" + integer;
                                blockingQueue.put(put);
                                System.out.println("put:" + put);
                                TimeUnit.SECONDS.sleep(1);
                            } catch (InterruptedException e) {
                                System.out.println("Interrupted Exception");
                                break;
                            }
                        }
                    }
                }).forEach(Thread::start);
        IntStream.rangeClosed(0, 10)
                .boxed()
                .map(integer -> new Thread("Thread-" + integer) {
                    @Override
                    public void run() {
                        while (true) {
                            try {
                                String take = blockingQueue.take();
                                System.out.println("take:" + take);
                                TimeUnit.SECONDS.sleep(1);
                            } catch (InterruptedException e) {
                                System.out.println("Interrupted Exception");
                                break;
                            }
                        }
                    }
                }).forEach(Thread::start);

    }

}
